<?php

namespace SC\Venus\Console;

use Illuminate\Support\Str;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;


class ViewCommand extends Command
{
    protected $signature = 'venus:view {name}';
    protected $description = 'Add venus views for controller';

    public function handle(FileSystem $fs)
    {
        $name = Str::studly(Str::singular($this->argument('name')));
        $uriName = Str::plural(Str::kebab($name));
        if (!\file_exists(\venus_view_path())) {
            $fs->makeDirectory(\venus_view_path());
        }

        if (!\file_exists(\venus_view_path($uriName))) {
            $fs->makeDirectory(\venus_view_path($uriName));
            $this->info('create directory ' . venus_view_path($uriName));
        }

        foreach(['index', 'show', 'form'] as $viewName) {
            $dstPath = \venus_view_path($uriName . '/' . $viewName . '.blade.php');
            if (!\file_exists($dstPath)) {
                $content = $fs->get(\venus_stub_path($viewName . '-view.php.stub'));
                $fs->put($dstPath, $this->renderView($name, $uriName, $content));
                $this->info('create file '. $dstPath);
            } else {
                $this->error('file ' . $dstPath . ' already exists');
            }
        }
    }

    public function renderView($name, $uriName, $content)
    {
        return str_replace(['{{{name}}}', '{{{uriName}}}'], [$name, $uriName], $content);
    }
}